//
//  UIViewController+KeyBoardHelp.m
//  playcar
//
//  Created by ddkj on 2018/7/31.
//  Copyright © 2018年 ljkj. All rights reserved.
//

#import "UIViewController+KeyBoardHelp.h"

@implementation UIViewController (KeyBoardHelp)

- (ShowKeyBoardBlock)showBlock {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setShowBlock:(ShowKeyBoardBlock)showBlock {
    objc_setAssociatedObject(self, @selector(showBlock), showBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (HideKeyBoardBlock)hideBlock {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setHideBlock:(HideKeyBoardBlock)hideBlock {
    objc_setAssociatedObject(self, @selector(hideBlock), hideBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void)registKeyBoardNotification:(ShowKeyBoardBlock)showKeyBoardBlock hideKeyBoardBlock:(HideKeyBoardBlock)hideKeyBoardBlock {
    
    self.showBlock = showKeyBoardBlock;
    self.hideBlock = hideKeyBoardBlock;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDidAppearNotifications:)
                                                 name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardDidHidenNotifications:)
                                                 name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardDidAppearNotifications:(NSNotification *)notifications {
    NSDictionary *userInfo = [notifications userInfo];
    CGFloat keyboardH = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    if (self.showBlock) {
        self.showBlock(keyboardH);
    }
}

- (void)keyboardDidHidenNotifications:(NSNotification *)notifications {
    if (self.hideBlock) {
        self.hideBlock();
    }
}

- (void)cancelKeyBoardNotification {
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardDidShowNotification
                                                  object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self
                                                    name:UIKeyboardDidHideNotification
                                                  object:nil];
}

@end
